package com.gitee.cui.security.netty.https;

import com.gitee.cui.config.SystemConfig;
import com.gitee.cui.ssl.SSLContextHelper;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

/**
 * 基于Netty实现的HTTPS回显程序服务端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 16:53
 **/
public class NettyHttpsServer {

    public static void startServer() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .localAddress(SystemConfig.SOCKET_SERVER_PORT)
                    .childHandler(new HttpsInitializer());
            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    private static class HttpsInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SSLContext context = SSLContextHelper.createServerSSLContext();
            SSLEngine engine = context.createSSLEngine();
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(false);
            pipeline.addLast(new SslHandler(engine));
            pipeline.addLast(new HttpServerCodec());
            // 将所有的http请求对象聚合成一个
            pipeline.addLast(new HttpObjectAggregator(65535));
            pipeline.addLast(new HttpEchoHandler());
        }
    }
}
